<template>
  <div class="breeding-container" style="max-width: 1200px; margin: 0 auto;">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner">⏳</div>
      <div class="loading-text">正在加载养殖信息...</div>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <div class="error-icon">❌</div>
      <div class="error-text">{{ error }}</div>
      <button class="retry-btn" @click="getBreedingInfoByBatch(props.batchNumber)">重试</button>
    </div>



    <!-- 养殖信息 -->
    <div class="info-section">
      <div class="section-header">
        <span class="section-title">养殖信息</span>
        <span class="edit-btn" @click="editBreedingInfo">设置</span>
      </div>
      <div class="info-content">
        <div class="info-grid">
          <div class="info-item">
            <span class="label">品种：</span>
            <span class="value">{{ breedingInfo.species }}</span>
          </div>
          <div class="info-item">
            <span class="label">来源：</span>
            <span class="value">{{ breedingInfo.source }}</span>
          </div>
          <div class="info-item">
            <span class="label">饲养天数：</span>
            <span class="value">{{ breedingInfo.feedingDays }}天</span>
          </div>
          <div class="info-item">
            <span class="label">饲料品牌：</span>
            <span class="value">{{ breedingInfo.feedingBrand }}</span>
          </div>
          <div class="info-item">
            <span class="label">饲养负责人：</span>
            <span class="value">{{ breedingInfo.feedingManager }}</span>
          </div>
          <div class="info-item">
            <span class="label"> 出栏日期：</span>
            <span class="value">{{ breedingInfo.marketingDate }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 保健信息 -->
    <div class="info-section">
      <div class="section-header">
        <span class="section-title">保健信息</span>
        <span class="add-btn-small" @click="addHealthRecord">新增行</span>
      </div>
      <div class="table-container">
        <table class="health-table">
          <thead>
            <tr>
              <th>饲养天数</th>
              <th>保健方式</th>
              <th>保健方法</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="record in healthRecords" :key="record.id">
              <!-- 编辑模式 -->
              <template v-if="editingRecord === record.id">
                <td><input type="text" v-model="editingData.days" placeholder="输入饲养天数" class="edit-input"></td>
                <td><input type="text" v-model="editingData.method" placeholder="输入保健方式" class="edit-input"></td>
                <td><input type="text" v-model="editingData.details" placeholder="输入保健方法" class="edit-input"></td>
                <td>
                  <button class="action-btn save-btn" @click="saveEditHealthRecord">保存</button>
                  <button class="action-btn cancel-btn" @click="cancelEditHealthRecord">取消</button>
                </td>
              </template>
              <!-- 显示模式 -->
              <template v-else>
                <td>{{ record.days }}</td>
                <td>{{ record.method }}</td>
                <td>{{ record.details }}</td>
                <td>
                  <button class="action-btn edit-btn" @click="editHealthRecord(record.id)">修改</button>
                  <button class="action-btn delete-btn" @click="deleteHealthRecord(record.id)">删除</button>
                </td>
              </template>
            </tr>
            <tr v-if="showAddRow">
              <td><input type="text" v-model="newHealthRecord.days" placeholder="输入饲养天数"></td>
              <td><input type="text" v-model="newHealthRecord.method" placeholder="输入保健方式"></td>
              <td><input type="text" v-model="newHealthRecord.details" placeholder="输入保健方法"></td>
              <td>
                <button class="action-btn save-btn" @click="saveHealthRecord">保存</button>
                <button class="action-btn cancel-btn" @click="cancelAddRow">取消</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 动检证 -->
    <div class="info-section">
      <div class="section-header">
        <span class="section-title">动检证</span>
      </div>
      <div class="certificate-content">
        <!-- 加载状态 -->
        <div v-if="certificateImagesLoading" class="certificate-loading">
          <div class="loading-spinner">⏳</div>
          <div class="loading-text">正在加载动检证图片...</div>
        </div>
        
        <!-- 已上传的动检证图片 -->
        <div v-else v-for="(image, index) in certificateImages" :key="index" class="certificate-item">
          <div class="certificate-preview">
            <img :src="image.url" :alt="`动检证${index + 1}`" class="certificate-img" />
            <div class="close-btn" @click="removeCertificateImage(index)">×</div>
          </div>
        </div>

        <!-- 添加按钮 -->
        <el-upload
          class="certificate-upload"
          action="http://localhost:34405/api/Image/upload-with-info"
          :show-file-list="false"
          :on-success="handleCertificateImageSuccess"
          :on-error="handleCertificateImageError"
          :on-progress="handleCertificateUploadProgress"
          :before-upload="beforeCertificateUpload"
          :data="getCertificateUploadData"
          name="file"
          accept="image/*"
          method="post"
          :headers="uploadHeaders"
        >
          <div class="add-certificate">
            <div class="add-btn" v-if="certificateUploadProgress === 0">
              <span class="plus-icon">+</span>
            </div>
            <div class="upload-progress-mini" v-else>
              <div class="progress-circle-mini">{{ certificateUploadProgress }}%</div>
            </div>
          </div>
        </el-upload>

        <!-- 信息徽章 -->
        <div class="info-badge">
          <span class="badge-number">{{ certificateImages.length }}</span>
        </div>
      </div>
    </div>

    <!-- 企业信息 -->
    <div class="info-section">
      <div class="section-header">
        <span class="section-title">企业信息</span>
        <span class="edit-btn" @click="editCompanyInfo">设置</span>
      </div>
      <div class="info-content">
        <div class="info-grid">
          <div class="info-item">
            <span class="label">养殖场：</span>
            <span class="value">{{ companyInfo.farmName }}</span>
          </div>
          <div class="info-item">
            <span class="label">负责人：</span>
            <span class="value">{{ companyInfo.manager }}</span>
          </div>
          <div class="info-item">
            <span class="label">存栏数量：</span>
            <span class="value">{{ companyInfo.stockQuantity }}只</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 企业照片 -->
    <div class="info-section">
      <div class="section-header">
        <span class="section-title">企业照片</span>
      </div>
      <div class="photos-content">
        <!-- 加载状态 -->
        <div v-if="photoImagesLoading" class="photo-loading">
          <div class="loading-spinner">⏳</div>
          <div class="loading-text">正在加载企业照片...</div>
        </div>
        
        <!-- 已上传的企业照片 -->
        <div v-else v-for="(image, index) in photoImages" :key="index" class="photo-item">
          <div class="photo-preview">
            <img :src="image.url" :alt="`企业照片${index + 1}`" class="photo-img" />
            <div class="close-btn" @click="removePhotoImage(index)">×</div>
          </div>
        </div>

        <!-- 添加按钮 -->
        <el-upload
          class="photo-upload"
          action="http://localhost:34405/api/Image/upload-with-info"
          :show-file-list="false"
          :on-success="handlePhotoImageSuccess"
          :on-error="handlePhotoImageError"
          :on-progress="handlePhotoUploadProgress"
          :before-upload="beforePhotoUpload"
          :data="getPhotoUploadData"
          name="file"
          accept="image/*"
          method="post"
          :headers="uploadHeaders"
        >
          <div class="add-photo">
            <div class="add-btn" v-if="photoUploadProgress === 0">
              <span class="plus-icon">+</span>
            </div>
            <div class="upload-progress-mini" v-else>
              <div class="progress-circle-mini">{{ photoUploadProgress }}%</div>
            </div>
          </div>
        </el-upload>

        <!-- 信息徽章 -->
        <div class="info-badge">
          <span class="badge-number">{{ photoImages.length }}</span>
        </div>
      </div>
    </div>
      <!-- 养殖信息编辑对话框 -->
    <div v-if="showBreedingDialog" class="dialog-overlay">
      <div class="dialog-content">
        <div class="dialog-header">
          <h3>养殖信息设置</h3>
          <button class="close-button" @click="showBreedingDialog = false">×</button>
        </div>
        <div class="dialog-body">
          <div class="form-row">
            <div class="form-label">品种：</div>
            <div class="form-input">
              <input type="text" v-model="dialogForm.species" placeholder="请输入品种" />
            </div>
          </div>
          <div class="form-row">
            <div class="form-label">来源：</div>
            <div class="form-input">
              <input type="text" v-model="dialogForm.source" placeholder="请输入来源" />
            </div>
          </div>
          <div class="form-row">
            <div class="form-label">饲养天数：</div>
            <div class="form-input">
              <input type="number" v-model="dialogForm.feedingDays" placeholder="请输入饲养天数" min="1" />
            </div>
          </div>
          <div class="form-row">
            <div class="form-label">饲料品牌：</div>
            <div class="form-input">
              <input type="text" v-model="dialogForm.feedingBrand" placeholder="请输入饲料品牌" />
            </div>
          </div>
          <div class="form-row">
            <div class="form-label">饲养负责人：</div>
            <div class="form-input">
              <input type="text" v-model="dialogForm.feedingManager" placeholder="请输入饲养负责人" />
            </div>
          </div>
          <div class="form-row">
            <div class="form-label">出栏日期：</div>
            <div class="form-input">
              <input type="date" v-model="dialogForm.marketingDate" placeholder="请输入出栏日期" />
            </div>
          </div>
        </div>
        <div class="dialog-footer">
          <button class="cancel-btn" @click="showBreedingDialog = false">取消</button>
          <button class="save-btn" @click="saveBreedingInfo">保存</button>
        </div>
      </div>
    </div>

    <!-- 企业信息编辑对话框 -->
    <div v-if="showCompanyDialog" class="dialog-overlay">
      <div class="dialog-content">
        <div class="dialog-header">
          <h3>企业信息</h3>
          <button class="close-button" @click="showCompanyDialog = false">×</button>
        </div>
        <div class="dialog-body">
          <div class="form-row">
            <div class="form-label"><span class="required">*</span>养殖场：</div>
            <div class="form-input">
              <input type="text" v-model="companyDialogForm.farmName" placeholder="四川祥泽养殖基地" />
            </div>
          </div>
          <div class="form-row">
            <div class="form-label"><span class="required">*</span>负责人：</div>
            <div class="form-input">
              <input type="text" v-model="companyDialogForm.manager" placeholder="X总" />
            </div>
          </div>
          <div class="form-row">
            <div class="form-label"><span class="required">*</span>存栏数量（只）：</div>
            <div class="form-input">
              <input type="number" v-model="companyDialogForm.stockQuantity" placeholder="32000" min="1" />
            </div>
          </div>
        </div>
        <div class="dialog-footer">
          <button class="cancel-btn" @click="showCompanyDialog = false">取消</button>
          <button class="save-btn" @click="saveCompanyInfo">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, defineProps, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { apiWreit } from '@/Ulter/AxiosHepler'

// 定义健康记录类型
interface HealthRecord {
  id: number
  days: string
  method: string
  details: string
}

// 定义props接收batchNumber参数
const props = defineProps<{
  batchNumber: string
}>()

// 控制对话框显示的变量
const showBreedingDialog = ref(false)
const showCompanyDialog = ref(false)

// 对话框表单数据
const dialogForm = reactive({
  species: '',
  source: '',
  feedingDays: 0,
  feedingBrand: '',
  feedingManager: '',
  marketingDate: ''
})

// 企业信息对话框表单数据
const companyDialogForm = reactive({
  farmName: '',
  manager: '',
  stockQuantity: 0
})

// 养殖信息数据 - 清空默认数据
const breedingInfo = reactive({
  species: '',
  source: '',
  feedingDays: 0,
  feedingBrand: '',
  feedingManager: '',
  marketingDate: ''
})

// 企业信息数据 - 清空默认数据
const companyInfo = reactive({
  farmName: '',
  manager: '',
  stockQuantity: 0
})

// 保健信息数据 - 清空默认数据
const healthRecords = ref<HealthRecord[]>([])

// 数据加载状态
const loading = ref(false)
const error = ref('')

const showAddRow = ref(false)

// 动检证图片相关变量
const certificateImages = ref<Array<{url: string, imageBatch: string, traceStage: string, traceType: string}>>([])
const certificateImagesLoading = ref(false)
const certificateUploadProgress = ref(0)

// 企业照片相关变量
const photoImages = ref<Array<{url: string, imageBatch: string, traceStage: string, traceType: string}>>([])
const photoImagesLoading = ref(false)
const photoUploadProgress = ref(0)

// 上传请求头
const uploadHeaders = {
  'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
}
const savingHealth = ref(false) // 保存保健信息的加载状态
const newHealthRecord = reactive({
  days: '',
  method: '',
  details: ''
})

// 打开养殖信息编辑对话框
const editBreedingInfo = () => {
  // 填充表单数据
  dialogForm.species = breedingInfo.species
  dialogForm.source = breedingInfo.source
  dialogForm.feedingDays = breedingInfo.feedingDays
  dialogForm.feedingBrand = breedingInfo.feedingBrand
  dialogForm.feedingManager = breedingInfo.feedingManager
  dialogForm.marketingDate = breedingInfo.marketingDate

  // 打开对话框
  showBreedingDialog.value = true
}

const addHealthRecord = () => {
  showAddRow.value = true
  // 重置表单
  newHealthRecord.days = ''
  newHealthRecord.method = ''
  newHealthRecord.details = ''
}

// 编辑状态管理
const editingRecord = ref<number | null>(null)
const editingData = reactive({
  days: '',
  method: '',
  details: ''
})

const editHealthRecord = (id: number) => {
  console.log('编辑保健记录:', id)
  
  // 找到要编辑的记录
  const recordToEdit = healthRecords.value.find(record => record.id === id)
  if (!recordToEdit) {
    ElMessage.warning('未找到要编辑的记录')
    return
  }

  // 设置编辑状态
  editingRecord.value = id
  editingData.days = recordToEdit.days
  editingData.method = recordToEdit.method
  editingData.details = recordToEdit.details

  console.log('开始编辑记录:', recordToEdit)
}

// 保存编辑
const saveEditHealthRecord = async () => {
  if (!editingRecord.value) {
    ElMessage.warning('没有正在编辑的记录')
    return
  }

  if (!editingData.days || !editingData.method || !editingData.details) {
    ElMessage.warning('请填写完整信息')
    return
  }

  if (!props.batchNumber) {
    ElMessage.warning('批次号不能为空')
    return
  }

  try {
    // 生成UUID函数
    const generateUUID = () => {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0
        const v = c === 'x' ? r : (r & 0x3 | 0x8)
        return v.toString(16)
      })
    }

    // 根据API文档准备修改数据
    const updateData = {
      displayName: "养殖保健", // 固定值
      breedingDays: parseInt(editingData.days),
      healthcareMethod: editingData.method.trim(),
      healthcareTechnique: editingData.details.trim(),
      batchNumber: props.batchNumber,
      modifiedTime: new Date().toISOString(),
      modifiedBy: localStorage.getItem('username') || 'system',
      operatedBy: localStorage.getItem('username') || 'system'
    }

    console.log('准备更新保健信息:', updateData)
    console.log('API请求URL:', `/api/BreedingHealthInfo/${editingRecord.value}`)
    console.log('请求方法:', 'PUT')

    // 调用PUT接口更新数据
    const response = await apiWreit.put(`/api/BreedingHealthInfo/${editingRecord.value}`, updateData, {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (response.status === 200 || response.status === 204) {
      ElMessage.success('保健信息修改成功')
      console.log('修改成功:', response.data)
      
      // 取消编辑状态
      editingRecord.value = null
      editingData.days = ''
      editingData.method = ''
      editingData.details = ''
      
      // 重新获取保健信息列表
      if (props.batchNumber) {
        await getHealthInfoByBatch(props.batchNumber)
      }
    } else {
      throw new Error('修改失败')
    }
  } catch (error: any) {
    console.error('修改保健信息失败:', error)
    
    if (error.response) {
      console.error('API响应错误:', error.response.data)
      ElMessage.error(`修改失败: ${error.response.data?.message || '未知错误'}`)
    } else {
      ElMessage.error('网络连接失败，请检查网络状态')
    }
  }
}

// 取消编辑
const cancelEditHealthRecord = () => {
  editingRecord.value = null
  editingData.days = ''
  editingData.method = ''
  editingData.details = ''
  console.log('取消编辑')
}

const deleteHealthRecord = async (id: number) => {
  try {
    // 找到要删除的记录
    const recordToDelete = healthRecords.value.find(record => record.id === id)
    if (!recordToDelete) {
      ElMessage.warning('未找到要删除的记录')
      return
    }

    console.log('准备删除的记录信息:', recordToDelete)

    // 确认删除对话框
    const confirmResult = await ElMessageBox.confirm(
      `确定要删除这条保健记录吗？\n饲养天数: ${recordToDelete.days}\n保健方式: ${recordToDelete.method}`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).catch(() => {
      console.log('用户取消删除操作')
      return false
    })

    if (!confirmResult) {
      return
    }

    console.log('准备删除保健记录ID:', id)
    console.log('API请求URL:', `/api/BreedingHealthInfo/${id}`)
    console.log('请求方法:', 'DELETE')

    // 调用删除API - 使用图片中显示的正确ID格式
    const response = await apiWreit.delete(`/api/BreedingHealthInfo/${id}`, {
      headers: {
        'Accept': 'text/plain'
      }
    })

    console.log('删除API响应:', response)
    console.log('响应状态码:', response.status)
    console.log('响应数据:', response.data)

    // 根据图片中的响应格式处理成功情况
    if (response.status === 200) {
      // 检查响应数据格式
      if (response.data && typeof response.data === 'object') {
        if (response.data.code === 200 && response.data.data === true) {
          ElMessage.success('保健记录删除成功')
          console.log('删除成功，服务器确认:', response.data.message)
        } else {
          ElMessage.warning(`删除操作完成，但服务器响应: ${response.data.message || '未知状态'}`)
        }
      } else if (response.data === true || response.data === 'true') {
        ElMessage.success('保健记录删除成功')
      } else {
        ElMessage.success('保健记录删除成功')
      }
      
      // 重新获取保健信息列表
      if (props.batchNumber) {
        console.log('重新获取保健信息列表...')
        await getHealthInfoByBatch(props.batchNumber)
      }
    } else if (response.status === 204) {
      // HTTP 204 No Content - 删除成功但无响应体
      ElMessage.success('保健记录删除成功')
      console.log('删除成功 (204 No Content)')
      
      // 重新获取保健信息列表
      if (props.batchNumber) {
        await getHealthInfoByBatch(props.batchNumber)
      }
    } else {
      throw new Error(`删除失败，状态码: ${response.status}`)
    }
  } catch (error: any) {
    console.error('删除保健记录失败:', error)
    
    if (error.response) {
      console.error('API响应错误详情:', {
        status: error.response.status,
        statusText: error.response.statusText,
        data: error.response.data,
        headers: error.response.headers
      })
      
      if (error.response.status === 404) {
        ElMessage.error('要删除的记录不存在')
      } else if (error.response.status === 400) {
        ElMessage.error('删除请求参数错误')
      } else if (error.response.status === 500) {
        ElMessage.error('服务器内部错误，请稍后重试')
      } else {
        ElMessage.error(`删除失败: ${error.response.data?.message || error.response.statusText || '未知错误'}`)
      }
    } else if (error.request) {
      console.error('网络请求错误:', error.request)
      ElMessage.error('网络连接失败，请检查网络状态')
    } else {
      console.error('其他错误:', error.message)
      ElMessage.error('删除保健记录失败，请重试')
    }
  }
}

const saveHealthRecord = async () => {
  if (!newHealthRecord.days || !newHealthRecord.method || !newHealthRecord.details) {
    ElMessage.warning('请填写完整信息')
    return
  }

  if (!props.batchNumber) {
    ElMessage.warning('批次号不能为空')
    return
  }

  savingHealth.value = true

  try {
    // 生成UUID函数
    const generateUUID = () => {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0
        const v = c === 'x' ? r : (r & 0x3 | 0x8)
        return v.toString(16)
      })
    }

    // 根据API文档生成完整的请求数据
    const healthData = {
      id: generateUUID(), // 动态生成UUID
      displayName: "养殖保健", // 固定值
      breedingDays: parseInt(newHealthRecord.days),
      healthcareMethod: newHealthRecord.method.trim(),
      healthcareTechnique: newHealthRecord.details.trim(),
      batchNumber: props.batchNumber,
      createdTime: new Date().toISOString(),
      modifiedTime: new Date().toISOString(),
      createdBy: localStorage.getItem('username') || 'system',
      modifiedBy: localStorage.getItem('username') || 'system',
      operatedBy: localStorage.getItem('username') || 'system'
    }

    console.log('准备保存保健信息:', healthData)
    console.log('API请求URL:', '/api/BreedingHealthInfo/Add')
    console.log('请求方法:', 'POST')

    // 调用Add接口
    const response = await apiWreit.post('/api/BreedingHealthInfo/Add', healthData, {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (response.status === 200 || response.status === 201) {
      // 重置表单
      newHealthRecord.days = ''
      newHealthRecord.method = ''
      newHealthRecord.details = ''
      showAddRow.value = false

      ElMessage.success('保健信息保存成功')
      console.log('保健信息保存成功:', response.data)
      
      // 重新获取保健信息列表
      if (props.batchNumber) {
        await getHealthInfoByBatch(props.batchNumber)
      }
    } else {
      throw new Error('保存失败')
    }
  } catch (error: any) {
    console.error('保存保健信息失败:', error)
    
    if (error.response) {
      console.error('API响应错误:', error.response.data)
      ElMessage.error(`保存失败: ${error.response.data?.message || '未知错误'}`)
    } else {
      ElMessage.error('网络连接失败，请检查网络状态')
    }
  } finally {
    savingHealth.value = false
  }
}

const cancelAddRow = () => {
  showAddRow.value = false
}

// 保存养殖信息
const saveBreedingInfo = async () => {
  // 验证表单数据
  if (!dialogForm.species || !dialogForm.source || dialogForm.feedingDays <= 0 || !dialogForm.feedingBrand || !dialogForm.feedingManager || !dialogForm.marketingDate) {
    ElMessage.warning('请填写完整信息')
    return
  }

  try {
    // 准备请求数据
    const requestData = {
      batchNumber: props.batchNumber,
      species: dialogForm.species,
      source: dialogForm.source,
      feedingDays: dialogForm.feedingDays,
      feedingBrand: dialogForm.feedingBrand,
      feedingManager: dialogForm.feedingManager,
      marketingDate: dialogForm.marketingDate
    }

    // 调用API
    const response = await apiWreit.post('http://localhost:34405/api/BreedingInfo', requestData)

    if (response.status === 200) {
      // 更新养殖信息
      breedingInfo.species = dialogForm.species
      breedingInfo.source = dialogForm.source
      breedingInfo.feedingDays = dialogForm.feedingDays
      breedingInfo.feedingBrand = dialogForm.feedingBrand
      breedingInfo.feedingManager = dialogForm.feedingManager
      breedingInfo.marketingDate = dialogForm.marketingDate

      // 关闭对话框
      showBreedingDialog.value = false

      // 显示成功消息
      ElMessage.success('养殖信息更新成功')
    } else {
      ElMessage.error('更新失败，请重试')
    }
  } catch (error) {
    console.error('API调用失败:', error)
    ElMessage.error('网络错误，请检查连接后重试')
  }
}

// 获取完整图片URL
const getFullImageUrl = (imagePath: string): string => {
  if (!imagePath) return ''
  if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
    return imagePath
  }
  return `http://localhost:34405${imagePath}`
}

// 动检证图片上传相关方法
const getCertificateUploadData = () => {
  const traceStage = '动检证'
  const traceType = `养殖信息_${traceStage}`
  console.log('动检证上传数据 - traceStage:', traceStage)
  console.log('动检证上传数据 - traceType:', traceType)
  return {
    imageBatch: props.batchNumber || '',
    traceStage: traceStage,
    traceType: traceType
  }
}

const beforeCertificateUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  certificateUploadProgress.value = 0
  return true
}

const handleCertificateImageSuccess = (response: any) => {
  console.log('动检证图片上传响应:', response)
  if (response && response.data) {
    const imageData = response.data
    const fullImageUrl = getFullImageUrl(imageData.imagePath)
    const traceStage = '动检证'
    const traceType = `养殖信息_${traceStage}`
    certificateImages.value.push({
      url: fullImageUrl,
      imageBatch: imageData.imageBatch || props.batchNumber || '',
      traceStage: imageData.traceStage || traceStage,
      traceType: imageData.traceType || traceType
    })
    console.log('动检证图片上传成功:', {
      url: fullImageUrl,
      batch: imageData.imageBatch,
      stage: imageData.traceStage,
      type: imageData.traceType
    })
    certificateUploadProgress.value = 0
    ElMessage.success('动检证上传成功!')
  } else {
    console.error('动检证上传失败，响应格式异常:', response)
    ElMessage.error('上传失败，未返回图片地址')
  }
}

const handleCertificateUploadProgress = (event: any) => {
  certificateUploadProgress.value = Math.round(event.percent)
}

const handleCertificateImageError = (error: any) => {
  console.error('动检证图片上传失败:', error)
  certificateUploadProgress.value = 0
  ElMessage.error('动检证上传失败，请重试')
}

const removeCertificateImage = async (index: number) => {
  try {
    const imageToDelete = certificateImages.value[index]
    if (!imageToDelete || !imageToDelete.url) {
      ElMessage.error('图片信息不完整，无法删除')
      return
    }

    // 从完整URL中提取imagePath
    let imagePath = imageToDelete.url
    if (imagePath.startsWith('http://localhost:34405')) {
      imagePath = imagePath.replace('http://localhost:34405', '')
    }

    console.log('准备删除动检证图片:', {
      index: index,
      imagePath: imagePath,
      fullUrl: imageToDelete.url
    })

    // 调用删除API
    const response = await apiWreit.delete('/api/Image/delete-by-path', {
      params: {
        imagePath: imagePath
      },
      headers: {
        'Accept': 'text/plain'
      }
    })

    console.log('删除动检证图片API响应:', response)

    if (response.status === 200) {
      // 从本地数组中移除图片
      certificateImages.value.splice(index, 1)
      ElMessage.success('动检证图片删除成功')
      console.log('动检证图片删除成功，已从本地列表移除')
    } else {
      throw new Error('删除失败')
    }
  } catch (error: any) {
    console.error('删除动检证图片失败:', error)
    if (error.response) {
      console.error('API响应错误:', error.response.data)
      ElMessage.error(`删除失败: ${error.response.data?.message || '未知错误'}`)
    } else {
      ElMessage.error('网络连接失败，请检查网络状态')
    }
  }
}

// 加载动检证图片
const loadCertificateImages = async () => {
  if (!props.batchNumber) {
    console.warn('批次号为空，无法查询动检证图片')
    return
  }
  certificateImagesLoading.value = true
  try {
    const traceStage = '动检证'
    const traceType = `养殖信息_${traceStage}`
    console.log('🔍 开始查询动检证图片:')
    console.log('  - 批次号:', props.batchNumber)
    console.log('  - traceStage:', traceStage)
    console.log('  - traceType:', traceType)
    const response = await apiWreit.get('/api/Image/GetByCondition', {
      params: {
        imageBatch: props.batchNumber,
        traceStage: traceStage,
        traceType: traceType
      }
    })
    if (response.status === 200 && response.data) {
      const images = response.data.data || response.data || []
      const processedImages = images.map((image: any) => ({
        url: getFullImageUrl(image.imagePath),
        imageBatch: image.imageBatch || props.batchNumber,
        traceStage: image.traceStage || traceStage,
        traceType: image.traceType || traceType
      }))
      certificateImages.value = processedImages
      console.log('✅ 动检证图片查询成功:', processedImages.length, '张图片')
      console.log('图片列表:', processedImages)
      if (processedImages.length === 0) {
        console.log('📝 暂无动检证图片')
      }
    } else {
      console.warn('查询动检证图片响应异常:', response)
      certificateImages.value = []
    }
  } catch (error: any) {
    console.error('❌ 查询动检证图片失败:', error)
    certificateImages.value = []
    if (error.response?.status === 404) {
      console.log('📝 未找到对应的动检证图片')
    } else {
      ElMessage.error('查询动检证图片失败')
    }
  } finally {
    certificateImagesLoading.value = false
  }
}

// 企业照片图片上传相关方法
const getPhotoUploadData = () => {
  const traceStage = '企业照片'
  const traceType = `养殖信息_${traceStage}`
  console.log('企业照片上传数据 - traceStage:', traceStage)
  console.log('企业照片上传数据 - traceType:', traceType)
  return {
    imageBatch: props.batchNumber || '',
    traceStage: traceStage,
    traceType: traceType
  }
}

const beforePhotoUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  photoUploadProgress.value = 0
  return true
}

const handlePhotoImageSuccess = (response: any) => {
  console.log('企业照片图片上传响应:', response)
  if (response && response.data) {
    const imageData = response.data
    const fullImageUrl = getFullImageUrl(imageData.imagePath)
    const traceStage = '企业照片'
    const traceType = `养殖信息_${traceStage}`
    photoImages.value.push({
      url: fullImageUrl,
      imageBatch: imageData.imageBatch || props.batchNumber || '',
      traceStage: imageData.traceStage || traceStage,
      traceType: imageData.traceType || traceType
    })
    console.log('企业照片图片上传成功:', {
      url: fullImageUrl,
      batch: imageData.imageBatch,
      stage: imageData.traceStage,
      type: imageData.traceType
    })
    photoUploadProgress.value = 0
    ElMessage.success('企业照片上传成功!')
  } else {
    console.error('企业照片上传失败，响应格式异常:', response)
    ElMessage.error('上传失败，未返回图片地址')
  }
}

const handlePhotoUploadProgress = (event: any) => {
  photoUploadProgress.value = Math.round(event.percent)
}

const handlePhotoImageError = (error: any) => {
  console.error('企业照片图片上传失败:', error)
  photoUploadProgress.value = 0
  ElMessage.error('企业照片上传失败，请重试')
}

const removePhotoImage = async (index: number) => {
  try {
    const imageToDelete = photoImages.value[index]
    if (!imageToDelete || !imageToDelete.url) {
      ElMessage.error('图片信息不完整，无法删除')
      return
    }

    // 从完整URL中提取imagePath
    let imagePath = imageToDelete.url
    if (imagePath.startsWith('http://localhost:34405')) {
      imagePath = imagePath.replace('http://localhost:34405', '')
    }

    console.log('准备删除企业照片图片:', {
      index: index,
      imagePath: imagePath,
      fullUrl: imageToDelete.url
    })

    // 调用删除API
    const response = await apiWreit.delete('/api/Image/delete-by-path', {
      params: {
        imagePath: imagePath
      },
      headers: {
        'Accept': 'text/plain'
      }
    })

    console.log('删除企业照片图片API响应:', response)

    if (response.status === 200) {
      // 从本地数组中移除图片
      photoImages.value.splice(index, 1)
      ElMessage.success('企业照片图片删除成功')
      console.log('企业照片图片删除成功，已从本地列表移除')
    } else {
      throw new Error('删除失败')
    }
  } catch (error: any) {
    console.error('删除企业照片图片失败:', error)
    if (error.response) {
      console.error('API响应错误:', error.response.data)
      ElMessage.error(`删除失败: ${error.response.data?.message || '未知错误'}`)
    } else {
      ElMessage.error('网络连接失败，请检查网络状态')
    }
  }
}

// 加载企业照片图片
const loadPhotoImages = async () => {
  if (!props.batchNumber) {
    console.warn('批次号为空，无法查询企业照片图片')
    return
  }
  photoImagesLoading.value = true
  try {
    const traceStage = '企业照片'
    const traceType = `养殖信息_${traceStage}`
    console.log('🔍 开始查询企业照片图片:')
    console.log('  - 批次号:', props.batchNumber)
    console.log('  - traceStage:', traceStage)
    console.log('  - traceType:', traceType)
    const response = await apiWreit.get('/api/Image/GetByCondition', {
      params: {
        imageBatch: props.batchNumber,
        traceStage: traceStage,
        traceType: traceType
      }
    })
    if (response.status === 200 && response.data) {
      const images = response.data.data || response.data || []
      const processedImages = images.map((image: any) => ({
        url: getFullImageUrl(image.imagePath),
        imageBatch: image.imageBatch || props.batchNumber,
        traceStage: image.traceStage || traceStage,
        traceType: image.traceType || traceType
      }))
      photoImages.value = processedImages
      console.log('✅ 企业照片图片查询成功:', processedImages.length, '张图片')
      console.log('图片列表:', processedImages)
      if (processedImages.length === 0) {
        console.log('📝 暂无企业照片图片')
      }
    } else {
      console.warn('查询企业照片图片响应异常:', response)
      photoImages.value = []
    }
  } catch (error: any) {
    console.error('❌ 查询企业照片图片失败:', error)
    photoImages.value = []
    if (error.response?.status === 404) {
      console.log('📝 未找到对应的企业照片图片')
    } else {
      ElMessage.error('查询企业照片图片失败')
    }
  } finally {
    photoImagesLoading.value = false
  }
}

const addCertificate = () => {
  console.log('添加证书')
}

const addPhoto = () => {
  console.log('添加照片')
}

// 打开企业信息编辑对话框
const editCompanyInfo = () => {
  // 填充表单数据
  companyDialogForm.farmName = companyInfo.farmName
  companyDialogForm.manager = companyInfo.manager
  companyDialogForm.stockQuantity = companyInfo.stockQuantity

  // 打开对话框
  showCompanyDialog.value = true
}

// 保存企业信息
const saveCompanyInfo = async () => {
  // 验证表单数据
  if (!companyDialogForm.farmName || !companyDialogForm.manager || companyDialogForm.stockQuantity <= 0) {
    ElMessage.warning('请填写完整信息')
    return
  }

  try {
    // 准备请求数据
    const requestData = {
      batchNumber: props.batchNumber,
      farmName: companyDialogForm.farmName,
      manager: companyDialogForm.manager,
      stockQuantity: companyDialogForm.stockQuantity
    }

    console.log('保存企业信息:', requestData)

    // 这里可以调用API保存企业信息
    // const response = await apiWreit.post('/api/CompanyInfo', requestData)

    // 暂时直接更新本地数据
    companyInfo.farmName = companyDialogForm.farmName
    companyInfo.manager = companyDialogForm.manager
    companyInfo.stockQuantity = companyDialogForm.stockQuantity

    // 关闭对话框
    showCompanyDialog.value = false

    // 显示成功消息
    ElMessage.success('企业信息更新成功')
  } catch (error) {
    console.error('保存企业信息失败:', error)
    ElMessage.error('网络错误，请检查连接后重试')
  }
}

// 根据批次号获取养殖信息
const getBreedingInfoByBatch = async (batchNumber: string) => {
  if (!batchNumber) {
    console.warn('批次号为空，无法获取养殖信息')
    return
  }

  loading.value = true
  error.value = ''

  try {
    console.log('正在获取批次号为', batchNumber, '的养殖信息...')
    
    // 调用API获取养殖信息
    const response = await apiWreit.get(`/api/BreedingInfo/search?batchNumber=${batchNumber}`)
    
    if (response.status === 200 && response.data) {
      console.log('API完整响应:', response.data)
      
      let data = null
      
      // 根据实际API结构处理数据
      if (response.data.data && Array.isArray(response.data.data) && response.data.data.length > 0) {
        // API返回 { data: [养殖信息对象] } 格式
        data = response.data.data[0]
        console.log('使用 response.data.data[0]:', data)
      } else if (response.data.data) {
        // API返回 { data: 养殖信息对象 } 格式
        data = response.data.data
        console.log('使用 response.data.data:', data)
      } else if (Array.isArray(response.data) && response.data.length > 0) {
        // API直接返回数组格式
        data = response.data[0]
        console.log('使用 response.data[0]:', data)
      } else {
        // API直接返回对象格式
        data = response.data
        console.log('使用 response.data:', data)
      }
      
      console.log('最终处理的数据:', data)
      
      if (data && typeof data === 'object') {
        // 更新养殖信息
        breedingInfo.species = data.species || '未知品种'
        breedingInfo.source = data.source || '未知来源'
        breedingInfo.feedingDays = data.feedingDays || 0
        breedingInfo.feedingBrand = data.feedingBrand || '未知品牌'
        breedingInfo.feedingManager = data.feedingManager || '未知负责人'
        
        // 处理日期格式
        if (data.marketingDate) {
          // 如果是ISO日期格式，转换为YYYY-MM-DD格式
          const date = new Date(data.marketingDate)
          if (!isNaN(date.getTime())) {
            breedingInfo.marketingDate = date.toISOString().split('T')[0]
          } else {
            breedingInfo.marketingDate = data.marketingDate
          }
        } else {
          breedingInfo.marketingDate = ''
        }

        // 更新企业信息（设置默认值，因为API可能不返回这些信息）
        companyInfo.farmName = data.farmName || '四川祥泽养殖基地'
        companyInfo.manager = data.manager || data.feedingManager || '未知负责人'
        companyInfo.stockQuantity = data.stockQuantity || 3200

        // 更新保健信息（设置默认的保健记录）
        if (data.healthRecords && Array.isArray(data.healthRecords)) {
          healthRecords.value = data.healthRecords.map((record: any, index: number) => ({
            id: record.id || index + 1,
            days: String(record.days || ''),
            method: record.method || '',
            details: record.details || ''
          }))
        } else {
          // 清空保健记录，不显示默认数据
          healthRecords.value = []
        }

        console.log('更新后的养殖信息:', {
          species: breedingInfo.species,
          source: breedingInfo.source,
          feedingDays: breedingInfo.feedingDays,
          feedingBrand: breedingInfo.feedingBrand,
          feedingManager: breedingInfo.feedingManager,
          marketingDate: breedingInfo.marketingDate
        })

        ElMessage.success('养殖信息加载成功')
      } else {
        console.warn('API返回的数据格式异常或为空:', data)
        ElMessage.warning(`未找到批次号 ${batchNumber} 的养殖信息`)
      }
    } else {
      throw new Error('API响应格式异常')
    }
  } catch (err: any) {
    console.error('获取养殖信息失败:', err)
    error.value = '获取养殖信息失败'
    
    if (err.response?.status === 404) {
      ElMessage.warning(`未找到批次号 ${batchNumber} 的养殖信息`)
    } else if (err.response?.status === 400) {
      ElMessage.error('请求参数错误')
    } else {
      ElMessage.error('网络错误，请检查连接后重试')
    }
  } finally {
    loading.value = false
  }
}

// 获取保健信息的方法
const getHealthInfoByBatch = async (batchNumber: string) => {
  if (!batchNumber) {
    ElMessage.warning('批次号不能为空')
    return
  }

  console.log('开始获取保健信息，批次号:', batchNumber)
  
  try {
    const response = await apiWreit.get(`/api/BreedingHealthInfo/search?batchNumber=${batchNumber}`)
    
    if (response.status === 200 && response.data) {
      console.log('保健信息API响应:', response.data)
      console.log('响应数据类型:', typeof response.data)
      console.log('是否为数组:', Array.isArray(response.data))
      
      // 处理返回的保健记录数据
      if (Array.isArray(response.data) && response.data.length > 0) {
        // 直接是数组格式
        console.log('使用直接数组格式解析数据')
        healthRecords.value = response.data.map((record: any, index: number) => {
          console.log(`处理记录 ${index + 1}:`, record)
          return {
            id: record.id || `temp_${index + 1}`,
            days: String(record.breedingDays || ''),
            method: record.healthcareMethod || '',
            details: record.healthcareTechnique || ''
          }
        })
        
        console.log('解析后的保健记录:', healthRecords.value)
        ElMessage.success(`成功加载 ${healthRecords.value.length} 条保健记录`)
      } else if (response.data.data && Array.isArray(response.data.data)) {
        // 嵌套在data字段中
        console.log('使用嵌套data格式解析数据')
        healthRecords.value = response.data.data.map((record: any, index: number) => {
          console.log(`处理记录 ${index + 1}:`, record)
          return {
            id: record.id || `temp_${index + 1}`,
            days: String(record.breedingDays || ''),
            method: record.healthcareMethod || '',
            details: record.healthcareTechnique || ''
          }
        })
        
        console.log('解析后的保健记录:', healthRecords.value)
        ElMessage.success(`成功加载 ${healthRecords.value.length} 条保健记录`)
      } else {
        // 没有找到保健记录
        console.log('未找到保健记录数据，设置为空数组')
        healthRecords.value = []
        ElMessage.info(`批次 ${batchNumber} 暂无保健记录`)
      }
    } else {
      throw new Error(`API响应状态异常: ${response.status}`)
    }
  } catch (error: any) {
    console.error('获取保健信息失败:', error)
    
    if (error.response) {
      if (error.response.status === 404) {
        healthRecords.value = []
        ElMessage.info(`批次 ${batchNumber} 暂无保健记录`)
      } else {
        ElMessage.error(`获取保健信息失败: ${error.response.data?.message || '未知错误'}`)
      }
    } else {
      ElMessage.error('网络连接失败，请检查网络状态')
    }
  }
}

// 监听批次号变化，当批次号可用时加载动检证图片和企业照片图片
watch(() => props.batchNumber, (newBatchNumber) => {
  if (newBatchNumber) {
    console.log('检测到批次号变化，准备加载动检证图片和企业照片图片:', newBatchNumber)
    setTimeout(() => {
      loadCertificateImages()
      loadPhotoImages()
    }, 500)
  }
}, { immediate: false })

// 组件挂载时获取数据
onMounted(async () => {
  console.log('Breeding组件挂载，接收到的批次号:', props.batchNumber)
  console.log('当前healthRecords数据:', healthRecords.value)
  
  if (props.batchNumber) {
    console.log('开始获取养殖信息和保健信息...')
    await getBreedingInfoByBatch(props.batchNumber)
    // 同时获取保健信息
    await getHealthInfoByBatch(props.batchNumber)
    // 加载动检证图片和企业照片图片
    setTimeout(() => {
      loadCertificateImages()
      loadPhotoImages()
    }, 500)
    console.log('数据获取完成，当前healthRecords:', healthRecords.value)
  } else {
    console.warn('未接收到批次号，将显示空白表单')
  }
})
</script>

<style scoped>
.breeding-container {
  display: flex;
  flex-direction: column;
  gap: 6px;
  padding: 10px;
  background-color: #ffffff;
  min-height: 100vh;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  background-color: #f9f9f9;
  border-radius: 8px;
  margin-bottom: 20px;
}

.loading-spinner {
  font-size: 32px;
  margin-bottom: 12px;
  animation: spin 1s linear infinite;
}

.loading-text {
  font-size: 16px;
  color: #666;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 错误状态样式 */
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  background-color: #fff2f0;
  border: 1px solid #ffccc7;
  border-radius: 8px;
  margin-bottom: 20px;
}

.error-icon {
  font-size: 32px;
  margin-bottom: 12px;
}

.error-text {
  font-size: 16px;
  color: #ff4d4f;
  margin-bottom: 16px;
}

.retry-btn {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.retry-btn:hover {
  background-color: #40a9ff;
}



.info-section {
  padding: 10px 0;
  flex: 1;
  min-width: 300px;
  width: 100%;
  margin-bottom: 6px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 6px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #1890ff;
}

.edit-btn {
  color: #1890ff;
  cursor: pointer;
  font-size: 14px;
  border: 1px solid #1890ff;
  padding: 2px 8px;
  border-radius: 4px;
}

.add-btn-small {
  color: #1890ff;
  cursor: pointer;
  font-size: 14px;
  border: 1px solid #1890ff;
  padding: 2px 8px;
  border-radius: 4px;
}

.info-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 6px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.label {
  font-weight: 500;
  color: #666;
  font-size: 14px;
}

.value {
  color: #333;
  font-size: 14px;
  line-height: 1.5;
}

.table-container {
  overflow-x: auto;
  margin-top: 6px;
}

.health-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #e8e8e8;
}

.health-table th,
.health-table td {
  padding: 8px;
  text-align: left;
  border: 1px solid #e8e8e8;
}

.health-table th {
  background-color: #f0f2f5;
  font-weight: 500;
  color: #333;
}

.action-btn {
  padding: 2px 8px;
  margin-right: 4px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.edit-btn {
  background-color: #e6f7ff;
  color: #1890ff;
  border-color: #bae7ff;
}

.delete-btn {
  background-color: transparent;
  color: #ff4d4f;
}

.save-btn {
  background-color: #1890ff;
  color: white;
}

.save-btn:disabled {
  background-color: #d9d9d9;
  color: #999;
  cursor: not-allowed;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #333;
}

.cancel-btn:disabled {
  background-color: #f0f0f0;
  color: #ccc;
  cursor: not-allowed;
}

input {
  padding: 6px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  width: 100%;
  box-sizing: border-box;
}

.edit-input {
  padding: 6px 8px;
  border: 1px solid #409eff;
  border-radius: 4px;
  font-size: 14px;
  background-color: #f8f9ff;
  transition: all 0.3s ease;
  width: 100%;
  box-sizing: border-box;
}

.edit-input:focus {
  outline: none;
  border-color: #66b1ff;
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.3);
}

.certificate-content,
.photos-content {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  margin-top: 6px;
}

.certificate-item,
.photo-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100px;
  height: 100px;
}

.certificate-img,
.photo-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.add-certificate,
.add-photo {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.add-btn {
  width: 100px;
  height: 100px;
  border: 2px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  background: #fafafa;
}

.add-btn:hover {
  border-color: #1890ff;
  color: #1890ff;
}

/* 动检证图片相关样式 */
.certificate-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 100px;
  background-color: #f9f9f9;
  border-radius: 4px;
  color: #666;
}

.certificate-loading .loading-spinner {
  font-size: 20px;
  margin-bottom: 8px;
  animation: spin 1s linear infinite;
}

.certificate-loading .loading-text {
  font-size: 12px;
  text-align: center;
}

.certificate-preview {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 4px;
  overflow: hidden;
}

.certificate-preview .certificate-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.certificate-preview .close-btn {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 20px;
  height: 20px;
  background-color: rgba(255, 0, 0, 0.8);
  color: white;
  border: none;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  cursor: pointer;
  z-index: 10;
}

.certificate-preview .close-btn:hover {
  background-color: rgba(255, 0, 0, 1);
}

.certificate-upload {
  display: inline-block;
}

.certificate-upload .add-certificate {
  position: relative;
  width: 100px;
  height: 100px;
  border: 2px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
  cursor: pointer;
  transition: all 0.3s;
}

.certificate-upload .add-certificate:hover {
  border-color: #1890ff;
  background: #f0f8ff;
}

.certificate-upload .plus-icon {
  font-size: 24px;
  color: #999;
  font-weight: bold;
}

.certificate-upload .add-certificate:hover .plus-icon {
  color: #1890ff;
}

.upload-progress-mini {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.progress-circle-mini {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #1890ff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
}

.info-badge {
  position: absolute;
  top: -8px;
  right: -8px;
  background-color: #ff4d4f;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
}

.badge-number {
  line-height: 1;
}

/* 企业照片图片相关样式 */
.photo-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 100px;
  background-color: #f9f9f9;
  border-radius: 4px;
  color: #666;
}

.photo-loading .loading-spinner {
  font-size: 20px;
  margin-bottom: 8px;
  animation: spin 1s linear infinite;
}

.photo-loading .loading-text {
  font-size: 12px;
  text-align: center;
}

.photo-preview {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 4px;
  overflow: hidden;
}

.photo-preview .photo-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.photo-preview .close-btn {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 20px;
  height: 20px;
  background-color: rgba(255, 0, 0, 0.8);
  color: white;
  border: none;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  cursor: pointer;
  z-index: 10;
}

.photo-preview .close-btn:hover {
  background-color: rgba(255, 0, 0, 1);
}

.photo-upload {
  display: inline-block;
}

.photo-upload .add-photo {
  position: relative;
  width: 100px;
  height: 100px;
  border: 2px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
  cursor: pointer;
  transition: all 0.3s;
}

.photo-upload .add-photo:hover {
  border-color: #1890ff;
  background: #f0f8ff;
}

.photo-upload .plus-icon {
  font-size: 24px;
  color: #999;
  font-weight: bold;
}

.photo-upload .add-photo:hover .plus-icon {
  color: #1890ff;
}

@media (max-width: 768px) {
  .breeding-container {
    flex-direction: column;
  }

  .info-section {
    width: 100%;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }
}

/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e8e8e8;
  background-color: #f0f8ff;
}

.dialog-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
  color: #1890ff;
}

.close-button {
  background: none;
  border: none;
  font-size: 20px;
  color: #999;
  cursor: pointer;
}

.dialog-body {
  padding: 20px;
}

.form-row {
  display: flex;
  margin-bottom: 16px;
  align-items: center;
}

.form-label {
  width: 100px;
  text-align: right;
  margin-right: 16px;
  font-weight: 500;
  color: #666;
}

.form-input {
  flex: 1;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 16px 20px;
  border-top: 1px solid #e8e8e8;
  background-color: #f9f9f9;
}

.cancel-btn,
.save-btn {
  padding: 6px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  margin-left: 10px;
}

.cancel-btn {
  background-color: #f5f5f5;
  border: 1px solid #d9d9d9;
  color: #666;
}

.save-btn {
  background-color: #1890ff;
  border: none;
  color: white;
}

/* 特殊标记样式 */
.step-number {
  background: #ffa500;
  color: white;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
  position: absolute;
  right: -12px;
  top: -12px;
}

.step-indicator {
  position: relative;
  width: 0;
  height: 0;
}

/* 必填字段星号样式 */
.required {
  color: #ff4d4f;
  margin-right: 4px;
  font-weight: bold;
}</style>

